import torch
import matplotlib.pyplot as plt

# 未知的规律
# -----------------散点图------------------
x = torch.linspace(-2, 2, 40)
y = 3 * x ** 2 + 1

plt.plot(x, y, 'ro')


# -----------------激活函数-------------------
def sigmoid(x):
    return 1 / (1 + torch.exp(-x))


# -----------------预测线--------------------
w_predict = 0.1  # 预测的w
b_predict = 0.2  # 预测的b

y_predict = sigmoid(w_predict * x + b_predict)
line, = plt.plot(x, y_predict, 'b--')

# ------------------不断改变斜率,查看e的变化-----
epochs = 100  # w改变一百次
for epoch in range(epochs):
    y_predict = sigmoid(w_predict * x + b_predict)
    # 让整体减去斜率
    # w新 = w旧 - 斜率 * 小固定值   ==>  SGD (随机梯度下降法)
    w_predict -= torch.mean(2 * x * (y_predict - y)) * 0.03
    b_predict -= torch.mean(2 * (y_predict - y)) * 0.03
    # 预测线不断改变
    line.set_data(x.detach().numpy(), y_predict.detach().numpy())
    # ------------------衡量预测线的准确率---------
    e = (y_predict - y) ** 2
    print(torch.mean(e))
    # 设置延迟时间
    plt.pause(0.5)
